package com.awccis.common.utils;

import java.io.File;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

import com.sun.mail.util.MailSSLSocketFactory;

/**
 * 使用SMTP协议发送电子邮件
 */
public class SendMailToAdmin {


    // 邮件发送协议
    private final static String PROTOCOL = "smtp";

    // SMTP邮件服务器
    private final static String HOST = JsonUtil.getJsonConfigValue("mailHost");
    //private final static String HOST = "smtp.163.com";

    // SMTP邮件服务器默认端口
    private final static String PORT = "465";

    // 是否要求身份认证
    private final static String IS_AUTH = "true";

    // 是否启用调试模式（启用调试模式可打印客户端与服务器交互过程时一问一答的响应消息）
    private final static String IS_ENABLED_DEBUG_MOD = "true";

    // 发件人
    private static String from = JsonUtil.getJsonConfigValue("mailFrom");

    // smtp用户名
    private static String smtpUser = JsonUtil.getJsonConfigValue("mailSmtpUser");

    // smtp用户名
    private static String smtpPassword = JsonUtil.getJsonConfigValue("mailSmtpPassword");

    // 初始化连接邮件服务器的会话信息
    private static Properties props = null;

    static {
        props = new Properties();
        props.setProperty("mail.transport.protocol", PROTOCOL);
        props.setProperty("mail.smtp.ssl.enable", "true");
        props.setProperty("mail.smtp.host", HOST);
        props.setProperty("mail.smtp.port", PORT);
        props.setProperty("mail.smtp.auth", IS_AUTH);
        props.setProperty("mail.debug",IS_ENABLED_DEBUG_MOD);
        String SSL_FACTORY="javax.net.ssl.SSLSocketFactory";
        props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.put("mail.smtp.socketFactory.port", "465");
        MailSSLSocketFactory sf;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", sf);
        } catch (GeneralSecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


    /**
     * 发送简单的文本邮件
     */
    public static boolean sendTextEmail(String to,String subject,String msg, boolean fileData, String pathName) throws Exception {
        try {
            //smtp认证
            Authenticator auth = new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication(){
                    //                           smtp认证： 用户名（完整邮箱地址）                                         授权码
                    return new PasswordAuthentication(smtpUser, smtpPassword);
                };
            };
            // 创建Session实例对象
            Session session = Session.getDefaultInstance(props,auth);

            // 创建MimeMessage实例对象
            MimeMessage message = new MimeMessage(session);
            // 设置发件人
            message.setFrom(new InternetAddress(from));
            // 设置邮件主题
            message.setSubject(subject);
            // 设置收件人
            message.setRecipient(RecipientType.TO, new InternetAddress(to));
            // 设置发送时间
            message.setSentDate(new Date());
            // 设置纯文本内容为邮件正文
            message.setText(msg);

            if(fileData) {
                //整封邮件的MINE消息体
                MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系
                //设置邮件的MINE消息体
                message.setContent(msgMultipart);

                //附件1
                MimeBodyPart attch1 = new MimeBodyPart();
                //正文内容
                MimeBodyPart content = new MimeBodyPart();

                //把内容，附件1，附件2加入到 MINE消息体中
                msgMultipart.addBodyPart(attch1);

                //添加正文
                msgMultipart.addBodyPart(content);

                //把文件，添加到附件1中
                //数据源
                DataSource ds1 = new FileDataSource(new File(pathName));
                //数据处理器
                DataHandler dh1 = new DataHandler(ds1 );
                //设置第一个附件的数据
                attch1.setDataHandler(dh1);
                //设置第一个附件的文件名
                String[] split = pathName.split("/");
                //attch1.setFileName(new String(split[split.length -1 ].getBytes("UTF-8"), "ISO-8859-1"));
                attch1.setFileName(MimeUtility.encodeText(split[split.length -1 ],"gb2312","B"));


                //正文（图片和文字部分）
                MimeMultipart bodyMultipart  = new MimeMultipart("related");
                //设置内容为正文
                content.setContent(bodyMultipart);

                //html代码部分
                MimeBodyPart htmlPart = new MimeBodyPart();
                //正文添加图片和html代码
                bodyMultipart.addBodyPart(htmlPart);

                //html代码
                htmlPart.setContent("<span style='color:black'>"+msg+"</span>","text/html;charset=utf-8");
            }

            // 保存并生成最终的邮件内容
            message.saveChanges();

            // 获得Transport实例对象
            Transport transport = session.getTransport();
            // 打开连接
            transport.connect();
            // 将message对象传递给transport对象，将邮件发送出去
            transport.sendMessage(message, message.getAllRecipients());
            // 关闭连接
            transport.close();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
